// 配额申请统计报表
import * as React from 'react';
import { useRef, useState, useEffect } from 'react';
import moment from 'moment'
import { getBrandSelectList, getDealerListByBrand } from '@/common/Request'
import './index.scss';
import { Button, Col, Form, Input, Row, DatePicker, Table, Select, Spin, message } from 'antd';
import { http } from '@/lib';
import apis from '@/apis/Report'
import { checkObj, toDateString } from '../helper';
import { downBlobFile } from '@/utils/methods';
const { MonthPicker, RangePicker } = DatePicker;
const { Option } = Select;
// 搜索框
function SearchBar(props) {
    // 修改父组件中的table源数据的方法
    const { changeFatherDataSource, page, size, changeSpinning, changeCount } = props;
    const [searchValue, setSearchValue] = useState(props.searchValue);
    // 保存销售组织列表
    const [brandList, setBrandList] = useState<any>([]);
    // 销售组织列表加载状态
    const [selectLoading, setSelectLoading] = useState(false);
    // 表单点击查询时候执行的方法
    const onSubmit = (e) => {
        e.preventDefault();
        
        // 将搜索值存放到session中
        sessionStorage.setItem('searchValueForQuota', JSON.stringify(searchValue));
        changeFatherDataSource(searchValue);
        
    }
    // 获取销售组织列表
    useEffect(() => {
        let UaaSysInfo = JSON.parse(sessionStorage.getItem("UaaSysInfo"));
        setBrandList(UaaSysInfo.profile.brandList);
        let flag = false;
        let se = sessionStorage.getItem('searchValueForQuota') ? JSON.parse(sessionStorage.getItem('searchValueForQuota')) : '';
        if (se) {
            if (se.checkTime.length > 0) {
                se.checkTime[0] = se.checkTime[0] && moment(se.checkTime[0]);
                se.checkTime[1] = se.checkTime[1] && moment(se.checkTime[1]);
            }
            
            setSearchValue(se);
            
            for (let key in se) {
                // console.log(se[key]);
                if (!(se[key] instanceof Array) && se[key] !== '' || (se[key] instanceof Array) && se[key].length > 0){
                    // console.log(se[key]);
                    flag = true;
                }
            }
            // setTimeout(() => {
            //     flag && changeFatherDataSource(se);
            // }, 0);
            changeFatherDataSource(se);
        }
        setTimeout(() => {
            !flag && changeFatherDataSource(searchValue);
         }, 0)
    }, [])
    const [mode, setMode] = useState(['month', 'month']);
    // const form = Form.createFormField()
    return (
        <div className="search-bar-form">
            <Form layout="inline" 
                name="formValue"
                // form={form}
                onSubmit={onSubmit}
            >
                <Row>
                    <Col offset={1} span={7}>
                        <Form.Item
                            label="销售组织"
                        >
                            {/* 这是一个下拉选 */}
                            <Select placeholder="请选择销售组织" onChange={(values:any) => { setSearchValue({...searchValue, brandCode: values})}} 
                                // style={{width:'200px', color: searchValue.brandCode == '' ? '#ccc' : ''}}
                                style={{width:'174px', color: searchValue.brandCode == '' ? '#ccc' : ''}}
                                allowClear={true}
                                loading={selectLoading}
                                disabled={selectLoading}
                                dropdownMatchSelectWidth={false}
                                value={searchValue.brandCode != '' ? searchValue.brandCode : '请选择销售组织'}
                            >
                                {brandList.map(({ brandCode, brandName }) => (<Option style={{width: '250px'}} key={brandCode} value={brandCode}>{brandName}</Option>))}
                            </Select>
                        </Form.Item>
                    </Col>
                    {/* <Col offset={1} span={7}>
                        <Form.Item
                            label="管理区域"
                        >
                            <Input placeholder="请输入关键词搜索" value={searchValue.belongAreaName} onChange={(e) => {setSearchValue({...searchValue, belongAreaName: e.target.value})}} />
                        </Form.Item>
                    </Col> */}
                    <Col offset={1} span={7}>
                        <Form.Item
                            label="配额周期"
                        >
                            <RangePicker
                                    placeholder={['开始月份', '结束月份']}
                                    value={searchValue.checkTime}
                                    mode={mode}
                                    onChange={(value) => {
                                        setSearchValue({...searchValue, checkTime: value || []});
                                    }}
                                    onOpenChange={(status) => {
                                        if(status) {
                                            setSearchValue({...searchValue, checkTime: []})
                                        }
                                    }}
                                    onPanelChange={(value, mode) => {
                                        // 判断选择的日期是否超过了今天
                                        if(value[0] as any > moment.now() || value[1]  as any > moment.now()) {
                                            message.warn('选择的日期不能超过当月')
                                        } else {
                                            setSearchValue({...searchValue, checkTime: value || []});
                                            setMode([mode[0] === 'date' ? 'month' : mode[0], mode[1] === 'date' ? 'month' : mode[1]]);
                                        }
                                    }}
                                    style={{width: '174px'}}
                                    format="YYYY-MM"
                                />
                        </Form.Item>
                    </Col>
                </Row>
                <Row align="middle" justify="space-around" gutter={24} style={{marginTop: '20px', borderTop: "1px solid #eee",borderBottom: "1px solid #eee", paddingTop: "4px", paddingBottom: "4px"}}>
                    <Col offset={10} span={12}>
                        <Button htmlType="submit" type="primary" style={{marginRight: '20px'}}>查询</Button>
                        <Button type="default"
                            onClick={() => {
                                setSearchValue({
                                    // 销售组织
                                    brandCode: '',
                                    // 管理区域
                                    belongAreaName: '',
                                    // 盘点周期 -> 盘点开始时间inventoryBegineTime  盘点结束时间inventoryEndTime
                                    checkTime: [],
                                })
                                sessionStorage.removeItem('searchValueForQuota')
                            }}
                        >重置</Button>
                    </Col>
                </Row>
            </Form>
        </div>
    )
}


const QuotaApllyReport = (props) => {
    // 设置table的标题样式
    // const TableTitleStyle = {fontWeight:'bolder', color:'#000', textAlign: 'center', alignItems: 'center'} as any;
    const TableTitleStyle = {} as any;
    // 设置已申请配额客户数量合未申请配额客户数量的ui样式
    const spanUI = {color: '#1890FF', cursor: 'pointer'} as any;
    const [searchValue, setSearchValue] = useState({
        // 销售组织
        brandCode: '',
        // 管理区域
        belongAreaName: '',
        // 盘点周期 -> 盘点开始时间inventoryBegineTime  盘点结束时间inventoryEndTime
        checkTime: [],
    })
    // 跳转方法
    const onTableSpanClick = (goWhere, record) => {
        if (goWhere === true) {
            // sessionStorage.setItem('hasNumberPlateListForQuota', JSON.stringify(record.inventoryCustomerBeanListVo?.hasNumberPlateList))
            // 跳转到已申请配额客户列表
            props.history.push({pathname: `/report/quotaapllyreport/appliedcustomerlist/${record.inventoryCustomerBeanListVo?.belongAreaCode}`, state: {record}});
        } else {
            // 跳转到未申请配额客户列表
            // sessionStorage.setItem('noNumberPlateListForQuota', JSON.stringify(record.inventoryCustomerBeanListVo?.noNumberPlateList))
            props.history.push({pathname: `/report/quotaapllyreport/notappliedcustomerlist/${record.inventoryCustomerBeanListVo?.belongAreaCode}`, state: {record}});
        }
    }
    useEffect(() => {
        return () => {
            sessionStorage.removeItem('hasNumberPlateListForQuota')
            sessionStorage.removeItem('noNumberPlateListForQuota')
            sessionStorage.removeItem('belongAreaCodeForQuota')
            // 离开界面的时候，判断url中是否包含stockcustomercountreport，如果包含则不用清除搜索的值
            if (props.history.location.pathname.indexOf("quotaapllyreport") === -1) {
                sessionStorage.removeItem("searchValueForQuota");
            }
        }
    }, [])
    // table的列标题
    const columns = [
        {
            title: <span style={TableTitleStyle}>销售组织</span>,
            key: 'brandName',
            dataIndex: 'brandName',
            align: 'center'
        },
        {
            title: <span style={TableTitleStyle}>管理区域</span>,
            key: 'belongAreaName',
            dataIndex: 'belongAreaName',
            align: 'center'
        },
        {
            title: <span style={TableTitleStyle}>配额周期</span>,
            key: 'quotaStartTime',
            align: 'center',
            render: (text, record, index) => {
                if (!record.quotaStartTime || !record.quotaEndTime) {
                    return '--'
                }
                let year = record.quotaStartTime.split('-')[0];
                let month = record.quotaStartTime.split('-')[1];
                return <span>{year + '年' + month + '月'}</span>
            }
        },
        {
            title: <span style={TableTitleStyle}>配额有效期</span>,
            key: 'quotaTerm',
            align: 'center',
            render: (text, record, index) => {
                if (!record.quotaStartTime || !record.quotaEndTime) {
                    return '--'
                }
                let start = record.quotaStartTime.split('-');
                start[2] = start[2].split(' ')[0];
                let end = record.quotaEndTime.split('-');
                end[2] = end[2].split(' ')[0];
                let s:string = '';
                start.forEach(item => {
                    s += item + '-';
                })
                end.forEach((item, index) => {
                    index !== end.length - 1 ? s += item + '-' : s += item;
                })
                s.slice(-1);
                return <span>{s}</span>
            }
        },
        {
            title: <span style={TableTitleStyle}>已申请配额客户数量</span>,
            key: 'hasAppliedForNumberOf',
            dataIndex: 'hasAppliedForNumberOf',
            align: 'center',
            render: (text, record, index) => {
                return <span style={spanUI} onClick={() => {
                    onTableSpanClick(true, record);
                }}>{text}</span>
            }
        },
        {
            title: <span style={TableTitleStyle}>未申请配额客户数量</span>,
            key: 'didNotApplyForNumber',
            dataIndex: 'didNotApplyForNumber',
            align: 'center',
            render: (text, record, index) => {
                return <span style={spanUI} onClick={() => {
                    onTableSpanClick(false, record);
                }}>{text}</span>
            }
        },
    ]
    // table的dataSource
    const [dataSource, setDataSource] = useState([]);
    // table的loading
    const [loading, setLoading] = useState(false);
    // table的pagination
    const [pagination, setPagination] = useState({
        page: 1, current: 1, pageSize: 10, showSizeChanger: true, showQuickJumper: true, pageSizeOptions: ['10', '20', '40', '60', '100', '150', '200'], total: 0,
        showTotal: (total, range) => `当前${range[0]}-${range[1]},共${total}项`
    });
    // 使用变量存储已申请配合客户数量和未申请配额客户数量
    const [appliedCustomerCount, setAppliedCustomerCount] = useState<any>('--')
    const [notAppliedCustomerCount, setNotAppliedCustomerCount] = useState<any>('--');
    const [firstCome, setFirstCome] = useState(true);
    const [search, setSearch] = useState(false);
    // 从服务器获取数据
    useEffect(() => {
        if (!firstCome) {
            setLoading(true);
            setExportLoading(true);
            let request:any = {
                page: pagination.page,
                size: pagination.pageSize,
            };
            let t:any = [];
            if (searchValue.checkTime.length > 0) {
                t = toDateString( searchValue.checkTime[0].format('YYYY-MM'),  searchValue.checkTime[1].format('YYYY-MM'));
            }
            
            if (searchValue.belongAreaName) {
                request.belongAreaName = searchValue.belongAreaName;
            }
            if (searchValue.brandCode) {
                request.brandCode = searchValue.brandCode;
            }
            if (t.length > 0) {
                request.quotaStartTime = t[0];
                request.quotaEndTime = t[1];
            }
            // 获取配额申请统计报表数据
            http.post(apis.GetQuotaDetailList, request)
                .then(res => {
                    let data = res.data.content;
                    let appliedCustomerCount = 0;
                    let notAppliedCustomerCount = 0;
                    data.forEach((item, index) => {
                        item.key = index;
                        appliedCustomerCount += parseInt(item.hasAppliedForNumberOf);
                        notAppliedCustomerCount += parseInt(item.didNotApplyForNumber);
                    });
                    setDataSource(data);
                    setPagination({...pagination, total: res.data.totalElements});
                    setAppliedCustomerCount(appliedCustomerCount);
                    setNotAppliedCustomerCount(notAppliedCustomerCount);
                    setLoading(false);
                    setExportLoading(false);
                }).catch(err => {
                    setLoading(false);
                    setExportLoading(false);
                })
            
            
        }
        firstCome && setFirstCome(false);
    }, [pagination.page, pagination.pageSize, search])
    
    // 修改table的datasouce的方法
    const changeFatherDataSource = (searchValue1) => {

        setSearchValue(searchValue1);
        if (pagination.page === 1) {
            setSearch(!search);
        }
        setPagination({...pagination, page: 1, current: 1});
        // setLoading(false);
    }
    // 点击查询显示等待
    const changeSpinning = () => {
        setLoading(true);
    }
    // 导出按钮的loading
    const [exportLoading, setExportLoading] = useState(false);
    // 导出盘点客户数量统计
    /**
     * @param type 1，2，3分别代表导出全部，导出已盘点，导出未盘点
     */
    const exportCustomerCountDetailExcel = (type: number) => {
        let t:any = [];
        if (searchValue.checkTime.length > 0) {
            t = toDateString( searchValue.checkTime[0].format('YYYY-MM'),  searchValue.checkTime[1].format('YYYY-MM'));
            let ss = searchValue.checkTime[0].format('YYYY-MM').split('-');
            let sy = parseInt(ss[0]);
            let sm = parseInt(ss[1]);
            let ee = searchValue.checkTime[1].format('YYYY-MM').split('-');
            let ey = parseInt(ee[0]);
            let em = parseInt(ee[1]);
            // 没有检查通过
            if (!checkObj(searchValue)){
                if(searchValue.brandCode && (ey - sy) * 12 + (em - sm) > 5) {
                    // 选择了品牌公司，则提示不能超过6个月
                    // message.error('请筛选周期，时间不能超过6个月');
                    return;
                } else if (!searchValue.brandCode && (ey - sy) * 12 + (em - sm) > 0){
                    // 什么都没选
                    // message.error('请筛选周期，时间不能超过1个月');
                    return;
                }
            }
        } else if(!checkObj(searchValue)){
            // message.warn("请选择盘点周期");
            return;
        }
        // if (searchValue.checkTime.length > 0) {
        //     t = toDateString( searchValue.checkTime[0].format('YYYY-MM'),  searchValue.checkTime[1].format('YYYY-MM'));
        //     let ss = searchValue.checkTime[0].format('YYYY-MM').split('-');
        //     let sy = parseInt(ss[0]);
        //     let sm = parseInt(ss[1]);
        //     let ee = searchValue.checkTime[1].format('YYYY-MM').split('-');
        //     let ey = parseInt(ee[0]);
        //     let em = parseInt(ee[1]);
        //     // 没有检查通过
        //     if (!checkObj(searchValue)){
        //         if(searchValue.brandCode && (ey - sy) * 12 + (em - sm) > 5) {
        //             // 选择了品牌公司，则提示不能超过6个月
        //             message.error('请筛选周期，时间不能超过6个月');
        //             return;
        //         } else if (!searchValue.brandCode && (ey - sy) * 12 + (em - sm) > 0){
        //             // 什么都没选
        //             message.error('请筛选周期，时间不能超过1个月');
        //             return;
        //         }
        //     }
        // } else if(!checkObj(searchValue)){
        //     message.warn("请选择盘点周期");
        //     return;
        // }
        // if (pagination.total === 0) {
        //     message.error("请先查找数据后再进行导出!");
        //     return;
        // }
        if (pagination.total > 30000) {
            message.error("数据超载不能导出，请重新筛选缩小数据范围");
            return;
        }
        
        // if (type === 1 && searchValue.checkTime.length === 0) {
        //     setExportLoading(false);
        //     message.error("请选择盘点周期查询之后，再进行导出");
        //     return
        // }
        // // 如果是选择已盘点或者未盘点的客户明细，则要提示选择一个指定的品牌
        // if (type === 2 || type == 3) {
        //     setExportLoading(false);
        //     if (searchValue.brandCode.length === 0 || !searchValue.belongAreaName) {
        //         message.error('请选择销售组织和管理区域查询之后，再进行导出');
        //         return;
        //     }
        //     if (searchValue.checkTime.length === 0) {
        //         message.error('请选择盘点周期查询之后，再进行导出');
        //         return;
        //     }
        // }
        
        let url:string = '';
        let fileName:string = '';
        let param:string = `?page=${1}&size=${30000}`;
        for (let key in searchValue) {
            if (searchValue[key] && !(searchValue[key] instanceof Array)) {
                param += `&${key}=${searchValue[key]}`;
            } else if (searchValue[key] instanceof Array && searchValue[key].length > 0) {
                let start = searchValue[key][0].format('YYYY-MM');
                let end = searchValue[key][1].format('YYYY-MM');
                let t = toDateString(start, end);
                param += `&inventoryBegineTime=${t[0]}&inventoryEndTime=${t[1]}`;
            }
        }

        
        if (type === 1) {
            setExportLoading(true);
            message.warn("导出中....请稍等");
            // 导出统计报表,get请求
            url = apis.DownloadQuotaRequestExcel;
            fileName = '配额申请统计报表';
            http.get(url + param, {responseType: 'arraybuffer', timeout: 1000 * 60 * 10 * 1000})
                .then(res => {
                    downBlobFile(res.data, fileName);
                    setExportLoading(false);
                    message.success("导出成功");
                })
                .catch(err => {
                    setExportLoading(false);
                    message.error("导出失败");
                })
        } else if (type === 2 || type === 3) {
            let request:any = {
                page: 1,
                size: 30000,
                belongAreaCode: dataSource[0]?.inventoryCustomerBeanListVo?.belongAreaCode
            }
            if (!searchValue.belongAreaName) {
                message.error("导出明细请选择一个指定的管理区域");
                return;
            }
            setExportLoading(true)
            message.warn("导出中....请稍等");
            let hasNumberPlateList:any = [];
            let noNumberPlateList:any = [];
            let data = dataSource;
            data.forEach((item, index) => {
                hasNumberPlateList = [...hasNumberPlateList, ...item.inventoryCustomerBeanListVo.hasNumberPlateList];
                noNumberPlateList = [...noNumberPlateList, ...item.inventoryCustomerBeanListVo.noNumberPlateList];
            })
            
            fileName = type === 2 ? `已申请客户明细` : `未申请客户明细`;
            if (type === 2) {request.hasNumberPlateList = hasNumberPlateList;}
            else if (type === 3) {request.noNumberPlateList = noNumberPlateList;}
            // post请求，将dataSource中的所有noNumberPlateList做成一个数组，所有hasNumberPlateList做成一个数组
            http.post(apis.HasAppliedForQuotaClientListExcel, request, {responseType:'arraybuffer'})
                .then(res => {
                    message.success('导出成功');
                    downBlobFile(res.data, fileName);
                    setExportLoading(false);
                })
                .catch(err => {
                    setExportLoading(false);
                })
        }
    }
    // 修改显示合计的方法
    const changeCount = (a:number, b:number) => {
        setAppliedCustomerCount(a);
        setNotAppliedCustomerCount(b);
    }
    return (
        <React.Fragment>
            <div className="QuotaApllyReport-title">
                配额申请统计报表
            </div>
            <SearchBar changeFatherDataSource={changeFatherDataSource} page={pagination.page} size={pagination.pageSize} searchValue={searchValue} changeSpinning={changeSpinning} changeCount={changeCount}/>
            <Spin spinning={exportLoading}>
                <div style={{marginTop: '10px', marginBottom: '10px'}}>
                        <Button type="primary" style={{borderLeft: '1px solid #fff'}} onClick={() => {
                            // 导出明细
                            setTimeout(() => {
                                exportCustomerCountDetailExcel(1);
                            }, 0);
                        }}>导出</Button>
                        <Button type="primary" style={{borderLeft: '1px solid #fff'}} onClick={() => {
                            // 导出已申请客户明细
                            setTimeout(() => {
                                exportCustomerCountDetailExcel(2);
                            }, 0);
                        }}>导出已申请客户明细</Button>
                        <Button type="primary" style={{borderLeft: '1px solid #fff'}} onClick={() => {
                            // 导出已申请客户明细
                            setTimeout(() => {
                                exportCustomerCountDetailExcel(3);
                            }, 0);
                        }}>导出未申请客户明细</Button>
                </div>
            </Spin>
            {/* 合计统计位置 */}
            <div className="QuotaApllyReport-total">
            <span className="total">合计: </span>已申请配额客户数量 <span>{appliedCustomerCount}</span> 未申请配额客户数量 <span>{notAppliedCustomerCount}</span>
            {/* <Button onClick={() => {
                console.log(searchValue);
            }}>查看</Button> */}
            </div>
            <Spin spinning={loading}>
                <Table 
                    columns={columns as any}
                    dataSource={dataSource}
                    pagination={pagination}
                    onChange={(pageOptions) => {
                        setPagination({
                            ...pagination,
                            pageSize: pageOptions.pageSize,
                            current: pageOptions.current,
                            page: pageOptions.current,
                        })
                    }}
                />
            </Spin>
        </React.Fragment>
    )
}

export default QuotaApllyReport;